package com.jyu.apts.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.jyu.apts.dao.ItemRepository;
import com.jyu.apts.entity.Item;
import com.jyu.apts.service.ItemService;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	ItemRepository itemDao;
	
	@Override
	public Item getOne(long id) {
		return itemDao.findById(id).get();
	}

	@Override
	public Page<Item> getItemPage(Integer pageNumber, Integer pageSize, Long organizationId, String search) {
		if(pageNumber == null || pageNumber <= 0) {
			pageNumber = 1;
		}
		if(pageSize == null || pageSize <= 0) {
			pageSize = 10;
		}
		Sort sort = new Sort(Sort.Direction.ASC,"id");
		PageRequest pageRequest = new PageRequest(pageNumber-1,pageSize,sort);
		Specification<Item> spec = new Specification<Item>() {
			@Override
			public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate pre = criteriaBuilder.conjunction();
				if(organizationId != null) {
					pre = criteriaBuilder.and(pre,criteriaBuilder.equal(root.get("organization").get("id"), organizationId.longValue()));
				}
				if(search!=null && search.trim().length()!=0) {
					Predicate or_pre = criteriaBuilder.disjunction(); 
					or_pre =criteriaBuilder.or(or_pre,criteriaBuilder.like(root.get("name"), "%"+search+"%"));
					pre = criteriaBuilder.and(pre,or_pre);
				}
				return pre;
			}
			
		};
		return itemDao.findAll(spec, pageRequest);
	}

	@Override
	public void save(Item item) {
		itemDao.saveAndFlush(item);
	}

	@Override
	public void save(List<Item> items) {
		itemDao.saveAll(items);
		itemDao.flush();
	}

	@Override
	public void delete(List<Item> items) {
		itemDao.deleteAll(items);
	}

	@Override
	public void delete(Item item) {
		itemDao.delete(item);
	}

	@Override
	public List<Item> findAll() {
		return itemDao.findAll();
	}

	@Override
	public List<Item> findAllById(List<Long> ids) {
		return itemDao.findAllById(ids);
	}

}
